// ---------------------------------------------------------------------
//
// -- 纹理管理
// -- author £
//
// ---------------------------------------------------------------------

let _lib = {},
    _curKey = '';

let TextureManager = {
    setCurKey: function (key) {
        _curKey = key;
    },

    getCurKey: function () {
        return _curKey;
    },

    updateGameTexture: function (key, url, sp) {
        this.updateTexture(_curKey, url, key, sp);
    },

    updateTexture: function (key, url, spKey, sp) {
        let obj, urls, textures, refs, sfs, exist;

        if (!_lib[key]) {
            obj = _lib[key] = {};
            obj.urls = [];
            obj.textures = [];
            obj.refs = {};
            obj.sfs = {};
        }
        
        urls = _lib[key].urls;
        textures = _lib[key].textures;
        refs = _lib[key].refs;

        sfs = _lib[key].sfs;
        refs[spKey] = url;

        if (urls.indexOf(url) < 0) {
            urls[urls.length] = url;
        }
                
        cc.loader.load({url: url, type: 'png'},
            function (error, texture) {
                if (error) {
                    return;
                }

                if (!_lib[key]) {
                    cc.loader.release(url);
                    texture.releaseTexture();
                    return;
                }

                if (textures.indexOf(texture) < 0) {
                    textures[textures.length] = texture;
                }

                if (url === refs[spKey]) {
                    let sf = new cc.SpriteFrame();

                    sf.setTexture(texture);

                    if (sp) {
                        sp.spriteFrame = sf;
                    }

                    sfs[spKey] = sf;
                }
            }.bind(this));
    },

    getGameTexture: function (key, url, sp) {
        this.getTexture(_curKey, url, key, sp);
    },

    //获取一张贴图
    getTexture: function (key, url, spKey, sp) {
        if (!_lib[key] || !_lib[key].sfs || !_lib[key].sfs[spKey]) {
            if (!url) return -1;

            this.updateTexture(key, url, spKey, sp);
            return;
        }
        
        if (sp) 
            sp.spriteFrame = _lib[key].sfs[spKey];
    },

    release: function (key) {
        if (!_lib[key]) return;

        let obj = _lib[key], i, len, textures, urls;
        
        obj.refs = null;
        delete obj.refs;
        obj.sfs = null;
        delete obj.sfs;
        textures = obj.textures;
        urls = obj.urls;
        len = textures.length;

        for (i = 0; i < len; ++i) {
            cc.loader.release(urls[i]);
            textures[i].releaseTexture();
        }

        obj.urls.length = 0;
        delete obj.urls;
        textures.length = 0;
        delete obj.textures;
        _lib[key] = null;
        delete _lib[key];
    },

    releaseGame: function () {
        this.release(this._curKey);
    },
};

module.exports = TextureManager; 